package com.beer.beerfriendfinder;

import static com.beer.beerfriendfinder.CommonUtilities.SENDER_ID;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.beer.beerfriendfinder.model.MUserModel;
import com.beer.beerfriendfinder.model.Users;
import com.google.android.gcm.GCMRegistrar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ViewFlipper;

public class LoginActivity extends Activity {
	
	// Activity Context
	Context context;
	final String TAG= "Login Activity TAG";
	MUserModel db;
	
	// Main control
	ViewFlipper vflipMainLogin;
	Animation slide_in_left, slide_out_right;
	Button cmdLogin,cmdRegister,cmdGotoRegister,cmdGotoLogin;
	// Edittext for register
	EditText txtRegisterEmail,txtRegisterPassword,txtRegisterRePassword,txtRegisterPhoneNumber;
	
	// Edittext for Login
	EditText txtLoginEmail,txtLoginPassword;
	
	/**
	 * register mode: flag = 2
	 * login mode: flag = 1 
	 */
	static int flag_flipper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initValue();
		Users us1 = db.getUser(1);
		if(us1!=null){
			Log.e(TAG, "ngon cmnr "+ us1.toJSONObject());
		}
		
		setId();
		setControlFunction();
		registerGCM();
	}

	/**
	 * set id for all control
	 */
	private void setId(){
		vflipMainLogin = (ViewFlipper) findViewById(R.id.vflipMainLogin);
		cmdLogin = (Button) findViewById(R.id.cmdLogin);		
		cmdRegister = (Button) findViewById(R.id.cmdRegister);
		cmdGotoRegister = (Button) findViewById(R.id.cmdGotoRegister);
		cmdGotoLogin = (Button) findViewById(R.id.cmdGotoLogin);
		
		// Register Edittext
		txtRegisterEmail = (EditText) findViewById(R.id.txtRegisterEmail);
		txtRegisterPassword = (EditText)  findViewById(R.id.txtRegisterPassword);
		txtRegisterRePassword = (EditText) findViewById(R.id.txtRegisterRePassword);
		txtRegisterPhoneNumber = (EditText) findViewById(R.id.txtRegisterPhoneNumber);
		
		// Login Edittext
		txtLoginEmail = (EditText) findViewById(R.id.txtLoginEmail);
		txtLoginPassword = (EditText) findViewById(R.id.txtLoginPassword);
	}
	
	/**
	 * set control function
	 */
	private void setControlFunction() {
		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		vflipMainLogin.setInAnimation(slide_in_left);
		vflipMainLogin.setOutAnimation(slide_out_right);
		
		// Flipper control
		cmdGotoLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// set mode to login
				flag_flipper = 1;
				
				vflipMainLogin.showPrevious();
			}
		});
		
		cmdGotoRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// set mode to register
				flag_flipper = 2;
				vflipMainLogin.showNext();
			}
		});
		
		// Register submit
		cmdRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(txtRegisterEmail.getText().toString().trim().length()<6){
					AlertDialogManager alert = new AlertDialogManager();
					alert.showAlertDialog(context, "No input Email", "Please insert email correctly", false);
					return;
				}
				if(txtRegisterPassword.getText().toString().trim().length()<6  || txtRegisterRePassword.getText().toString().trim().length()<6 || !txtRegisterPassword.getText().toString().trim().equals(txtRegisterRePassword.getText().toString().trim())){
					AlertDialogManager alert = new AlertDialogManager();
					alert.showAlertDialog(context, "No input Password", "Please insert password correctly", false);
					return;
				}
				if(txtRegisterPhoneNumber.getText().toString().trim().length()<6){
					AlertDialogManager alert = new AlertDialogManager();
					alert.showAlertDialog(context, "No input phone number", "Please insert phone number correctly", false);
					return;
				}
				
				List<NameValuePair> pairRegister = new ArrayList<NameValuePair>();
				pairRegister.add(new BasicNameValuePair("email", txtRegisterEmail.getText().toString().trim()));
				pairRegister.add(new BasicNameValuePair("password", txtRegisterPassword.getText().toString().trim()));
				pairRegister.add(new BasicNameValuePair("phoneNumber", txtRegisterPhoneNumber.getText().toString().trim()));
				
				try{
					if(taskRegister != null){
						taskRegister.cancel(true);
						taskRegister = null;
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				taskRegister = new TaskRegister(context, pairRegister);
				taskRegister.execute(null,null,null);
			}
		});
		
		// Login submit
		cmdLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(txtLoginEmail.getText().toString().trim().length() < 6){
					AlertDialogManager alert = new AlertDialogManager();
					alert.showAlertDialog(context, "No input Email", "Please insert email correctly", false);
					return;
				}
				
				if(txtLoginPassword.getText().toString().trim().length()<6  ){
					AlertDialogManager alert = new AlertDialogManager();
					alert.showAlertDialog(context, "No input Password", "Please insert password correctly", false);
					return;
				}
				
				int i = 0;
				while(ServerUrlConstant.regId.trim().equals("") && i <= 3){
					ServerUrlConstant.regId = GCMRegistrar.getRegistrationId(context);
					if(i==3){
						return;
					}else {
						i++;
					}
				}
				
				List<NameValuePair> pairLogin = new ArrayList<NameValuePair>();
				pairLogin.add(new BasicNameValuePair("email", txtLoginEmail.getText().toString().trim()));
				pairLogin.add(new BasicNameValuePair("password", txtLoginPassword.getText().toString().trim()));
				pairLogin.add(new BasicNameValuePair("regId", ServerUrlConstant.regId));
				
				try{
					if(taskLogin!=null){
						taskLogin.cancel(true);
						taskLogin = null;
					}
				}catch(Exception e){
					
				}
				taskLogin = new TaskLogin(context, pairLogin);
				taskLogin.execute(null,null,null);
			}
		});
	}
	
	/**
	 * init all value static and flag
	 */
	void initValue(){
		flag_flipper = 1;
		context = this;
		db = new MUserModel(this);
	}
	
	/**
	 * register with google cloud
	 * not register with current server
	 */
	void registerGCM(){
		ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
		AlertDialogManager alert = new AlertDialogManager();
		 
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(context,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
         
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
 
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
         
        // Get GCM registration id
        ServerUrlConstant.regId = GCMRegistrar.getRegistrationId(this);
        Log.e("regId","id: "+ServerUrlConstant.regId);
        
        
        // Check if regid already presents
        if (ServerUrlConstant.regId.equals("")) {
            // Registration is not present, register now with GCM          
            GCMRegistrar.register(this, SENDER_ID);
        } 
	}
	
	/**
	 * task register a user
	 * @author phuoctd
	 *
	 */
	class TaskRegister extends AsyncTask<Void, Void, Void>{
		
		List<NameValuePair> pairRegister;
		Context context;
		String url_register = ServerUrlConstant.URL_Server + "register_new.php";
		String result_from_server;
		
		TaskRegister(Context ctx, List<NameValuePair> pair){
			context = ctx;
			pairRegister = pair;
			result_from_server="";
		}

		@Override
		protected Void doInBackground(Void... params) {
			result_from_server = ServerUtilities.makeServiceCall(url_register, 2, pairRegister);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				JSONObject jsonObject = new JSONObject(result_from_server);
				if(jsonObject.getInt("success")==1){
					vflipMainLogin.showPrevious();
				}else{
					Log.e(TAG,"error = "+jsonObject.getString("error"));;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	TaskRegister taskRegister;
	
	class TaskLogin extends AsyncTask<Void, Void, Void>{
		
		Context context;
		List<NameValuePair> pairLogin;
		String url_login = ServerUrlConstant.URL_Server + "login.php";
		String result_from_server;
		
		public TaskLogin(Context ctx, List<NameValuePair> pair) {
			context = ctx;
			pairLogin = pair;
			result_from_server="";
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			result_from_server = ServerUtilities.makeServiceCall(url_login, 2, pairLogin);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				JSONObject jsonObject = new JSONObject(result_from_server);
				int i = jsonObject.getInt("success");
				if(i==1){
					JSONObject temp = jsonObject.getJSONObject("data");
					Users _user = new Users(temp);
					db.addNewUser(_user);
					Users new_user = db.getUser(_user.get_id());
					Log.e(TAG,new_user.toJSONObject());
					Intent intent = new Intent(context, MainActivity.class);
					startActivity(intent);
					finish();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
	}
	TaskLogin taskLogin;
}
